#include "platform.h"
#include "ui_platform.h"
#include"myscene.h"
#include<QKeyEvent>
#include<QGraphicsEllipseItem>
#include<QDebug>
#include<QGraphicsView>
#include<QLabel>
#include<QGraphicsItem>

#include<QTimer>
#include<QGraphicsSimpleTextItem>
#include<QtWidgets>
#include<QScrollBar>
platform::platform(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::platform)
{
    ui->setupUi(this);

    scene_init();
    view_init();
    connect_init();
}

platform::~platform()
{
    delete ui;
}

void platform::scene_init()
{
    scene=new MyScene();
    QRectF rectTmp = scene->sceneRect();	//获得当前view scene的区域
    QPointF ptTopLeft = rectTmp.topLeft();	//获得区域左上点和右下点坐标
    QPointF ptBottomRight = rectTmp.bottomRight();
    QPointF ptW_H = 5 * QPointF(rect().width(), rect().height());	//这一步主要是为了后边放大区域的范围，0.5这个系数可以修改
    ptTopLeft -= ptW_H;	//左上点向左上方平移
    ptBottomRight += ptW_H;	//右下点向右下平移
    rectTmp.setTopLeft(ptTopLeft);	//按照左上左下点修改rect的大小
    rectTmp.setBottomRight(ptBottomRight);
    scene->setSceneRect(rectTmp);//更新scene rect的范围
}

void platform::view_init()
{
    ui->gView->setDragMode(QGraphicsView::DragMode::ScrollHandDrag);
    ui->gView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->gView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    //scene->isShowGrid=0;
    ui->gView->setScene(scene);
    ui->gView->setCursor(Qt::CrossCursor);
    //鼠标跟踪
    ui->gView->setMouseTracking(true);
    //区域选择
    //ui->gView->setDragMode(QGraphicsView::RubberBandDrag);
    //抗锯齿
    ui->gView->setRenderHint(QPainter::Antialiasing);
}

void platform::connect_init()
{
    connect(ui->gView,SIGNAL(mouseDoubleClick(QMouseEvent *)),this,SLOT(on_mouseDoubleClick(QMouseEvent *)));
    connect(ui->gView,SIGNAL(mousePress(QMouseEvent *)),this,SLOT(on_mousePress(QMouseEvent *)));
    connect(ui->gView,SIGNAL(mouseMove(QMouseEvent *)),this,SLOT(on_mouseMove(QMouseEvent *)));
    connect(ui->gView,SIGNAL(keyPress(QKeyEvent *)),this,SLOT(on_keyPress(QKeyEvent *)));
    connect(ui->gView,SIGNAL(mouseRelease(QMouseEvent *)),this,SLOT(on_mouseRelease(QMouseEvent *)));
}

void platform::on_mouseDoubleClick(QMouseEvent *e)
{
    QPoint p=e->pos();//获得view坐标
    QPointF pointS=ui->gView->mapToScene(p);//坐标转换，view坐标转换成scene坐标
    Node *node=new Node(pointS);
    node->id=nodes.size();
    node->name->setPlainText(QString::asprintf("%d",node->id));
    scene->addItem(node->name);
    //场景中添加node
    scene->addItem(node);
    //列表中添加node
    nodes.append(node);
}


void platform::on_mousePress(QMouseEvent *e)
{

    QPoint p=e->pos();
    QPointF pointS=ui->gView->mapToScene(p);
    curID=-1;
    for(int i=0;i<nodes.size();i++)
    {
        int dx = pointS.x() - nodes[i]->pos.x();
        int dy = pointS.y() - nodes[i]->pos.y();
        int dist = sqrt(dx*dx+dy*dy);
        if(dist < size/2)
        {
            curID = i;
        }
    }
    if(curID!=-1)
    {
        if(e->button()==Qt::LeftButton)
        {
            isDragging=1;
            //ui->node_name->setText(QString::asprintf("当前选中：节点%d,scene坐标：%1.f,%1.f",curID,nodes[curID]->POS().x(),nodes[curID]->POS().y()));

        }
        else if(e->button()==Qt::RightButton)
        {

            if(!isDrawing)
            {
                 isDrawing=1;
                 //QPointF s=item_center;
                 edge=new Edge(nodes[curID]);
                 edge->s=curID;
                 scene->addItem(edge);
                 edges.append(edge);
            }
            else
            {
                isDrawing=0;
                edge->end=nodes[curID];
                edge->e=curID;
                QLineF newLine(edge->start->pos,edge->end->pos);
                edge->setLine(newLine);

                QPointF ss=edge->start->POS();
                QPointF ee=edge->end->POS();
                qreal x=(ss.x()+ee.x())/2;
                qreal y=(ss.y()+ee.y())/2;
                QPointF cc=QPointF(x,y);

                edge->weight->setPos(cc);

                scene->addItem(edge->weight);


            }

        }
    }
    else
    {
        return ;
    }

}



void platform::on_mouseMove(QMouseEvent *e)
{


    QPoint p=e->pos();
    QPointF pointS=ui->gView->mapToScene(p);
    if(curID!=-1)
    {
        if(isDrawing)
        {
            QLineF newLine(nodes[curID]->POS(), pointS);
            edge->setLine(newLine);
        }
        else if(isDragging)
        {
            qDebug()<<"拖拽";
            nodes[curID]->pos=pointS;
            nodes[curID]->setPos(QPointF(pointS.x()-size/2,pointS.y()-size/2));
            nodes[curID]->name->setPos(QPointF(pointS.x()-size/2-18,pointS.y()-size/2-18));
            qDebug()<<nodes[curID]->POS();

            for(int j=0;j<edges.size();j++)
            {

                qreal x1=edges[j]->start->pos.x();
                qreal y1=edges[j]->start->pos.y();
                qreal x2=edges[j]->end->pos.x();
                qreal y2=edges[j]->end->pos.y();
                QPointF cc((x1+x2)/2,(y1+y2)/2);
                QLineF newLine(edges[j]->start->pos,edges[j]->end->pos);
                edges[j]->setLine(newLine);
                edges[j]->weight->setPos(cc);
                scene->update();
            }

        }
    }

}

void platform::on_keyPress(QKeyEvent *e)
{
    if(e->key()==Qt::Key_E)
    {

    }
    if(e->key()==Qt::Key_Backspace)
    {
        //qDebug()<<e;
        int cnt=scene->selectedItems().count();
        if(cnt==0)
        {

            return;
        }
        else
        {
            for(int i=0;i<cnt;i++)
            {
                QGraphicsItem *item=scene->selectedItems().at(0);
                //qDebug()<<item->type();

                if(item->type()==QGraphicsEllipseItem::Type)
                {
                    QSet<int> pre_to_del;
                    if(curID==-1)
                        return ;
                    for(int j=0;j<edges.size();j++)
                    {
                        if(nodes[curID]==edges[j]->start || nodes[curID]==edges[j]->end)
                        {
                            scene->removeItem(edges[j]);
                            scene->removeItem(edges[j]->weight);
                            pre_to_del.insert(j);

                        }
                    }
                    if(!pre_to_del.isEmpty())
                    {
                        foreach(int v,pre_to_del)
                        {
                            edges.removeAt(v);
                        }
                    }
                    scene->removeItem(item);
                    scene->removeItem(nodes[curID]->name);
                    nodes.removeAt(curID);
                }
                else
                {
                    //continue;
                    if(item!=NULL)
                    scene->removeItem(item);
                }

            }

        }
    }
}

void platform::on_mouseRelease(QMouseEvent *e)
{
    isDragging=0;
}




void platform::on_big_act_triggered()
{
    ui->gView->scale(1.1,1.1);
}

void platform::on_small_act_triggered()
{
    ui->gView->scale(0.9,0.9);
}

void platform::on_grid_act_triggered()
{
    scene->isShowGrid=!(scene->isShowGrid);
    scene->update();
}
